/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hengtiansoft.lfy.chart.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.db.InviteMessgeDao;
import com.hengtiansoft.lfy.chart.domain.InviteMessage;
import com.hengtiansoft.lfy.chart.domain.InviteMessage.InviteMesageStatus;
import com.hengtiansoft.lfy.chart.utils.UserUtils;
import com.hyphenate.chat.EMClient;

import java.util.List;

public class NewFriendsMsgAdapter extends ArrayAdapter<InviteMessage> {

    private Context context;
    private InviteMessgeDao messgeDao;

    public NewFriendsMsgAdapter(Context context, int textViewResourceId,
                                List<InviteMessage> objects) {
        super(context, textViewResourceId, objects);
        this.context = context;
        messgeDao = new InviteMessgeDao(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(context, R.layout.row_invite_msg, null);
            holder.avator = (ImageView) convertView.findViewById(R.id.avatar);
            holder.reason = (TextView) convertView.findViewById(R.id.message);
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.status = (RelativeLayout) convertView
                    .findViewById(R.id.rl_add_friends);
            holder.groupContainer = (LinearLayout) convertView
                    .findViewById(R.id.ll_group);
            holder.groupname = (TextView) convertView
                    .findViewById(R.id.tv_groupName);
            holder.mTvAGREE = (TextView) convertView
                    .findViewById(R.id.tv_add_friends);
            holder.mIvAGREE = (ImageView) convertView
                    .findViewById(R.id.iv_add_friends);
            // holder.time = (TextView) convertView.findViewById(R.id.time);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        String str1 = context.getResources()
                .getString(R.string.Has_agreed_to_your_friend_request);
        String str2 = context.getResources().getString(R.string.agree);

        String str3 = context.getResources()
                .getString(R.string.Request_to_add_you_as_a_friend);
        String str4 = context.getResources()
                .getString(R.string.Apply_to_the_group_of);
        String str5 = context.getResources().getString(R.string.Has_agreed_to);
        String str6 = context.getResources().getString(R.string.Has_refused_to);
        final InviteMessage msg = getItem(position);
        if (msg != null) {
            if (msg.getGroupId() != null) { // 显示群聊提示
                holder.groupContainer.setVisibility(View.VISIBLE);
                holder.groupname.setText(msg.getGroupName());
            } else {
                holder.groupContainer.setVisibility(View.GONE);
            }

            holder.avator.setTag(msg.getFrom());
            // 通过 tag 来防止图片错位
            if (holder.avator.getTag() != null
                    && holder.avator.getTag().equals(msg.getFrom())) {
                UserUtils.getUserByUsernameRequest(context, msg.getFrom(),
                        holder.avator);
            }
            // holder.reason.setText(msg.getReason());
            holder.name.setText(msg.getFrom());
            // holder.time.setText(DateUtils.getTimestampString(new
            // Date(msg.getTime())));
            if (msg.getStatus() == InviteMesageStatus.BEAGREED) {//已对方已同意你的好友请求
                holder.status.setVisibility(View.INVISIBLE);
                holder.reason.setText(str1);

            } else if (msg.getStatus() == InviteMesageStatus.BEINVITEED
                    || msg.getStatus() == InviteMesageStatus.BEAPPLYED) { //同意对方申请按钮
                holder.status.setVisibility(View.VISIBLE);
                holder.status.setEnabled(true);
                holder.reason.setText("已同意对方请求");
                // holder.status
                // .setBackgroundResource(android.R.drawable.btn_default);
                holder.mTvAGREE.setText(str2);
                if (msg.getStatus() == InviteMesageStatus.BEINVITEED) {//对方请求加好友
                    // if (msg.getReason() == null) {
                    // 如果没写理由
                    holder.reason.setText(str3);
                    // }
                } else { // 入群申请
                    if (TextUtils.isEmpty(msg.getReason())) { //申请加入群
                        holder.reason.setText(str4 + msg.getGroupName());
                    }
                }
                // 设置点击事件
                holder.status.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 同意别人发的好友请求
                        acceptInvitation(holder.mIvAGREE, holder.status,
                                holder.mTvAGREE, msg);
                    }
                });
            } else if (msg.getStatus() == InviteMesageStatus.AGREED) {//我已同意对方请求
                holder.mTvAGREE.setText(str5);
                holder.mIvAGREE.setVisibility(View.GONE);
                holder.status.setEnabled(false);
                holder.reason.setText(context.getString(R.string.request_agreed));
            } else if (msg.getStatus() == InviteMesageStatus.REFUSED) {//我拒绝对方请求
                holder.mTvAGREE.setText(str6);
                holder.mIvAGREE.setVisibility(View.GONE);
                holder.status.setEnabled(false);
                holder.reason.setText(context.getString(R.string.request_refuse));
            }
        }

        return convertView;
    }

    /**
     * 同意好友请求或者群申请
     * 
     * @param
     * @param
     */
    private void acceptInvitation(final ImageView imageView,
                                  final RelativeLayout relativeLayout, final TextView textView,
                                  final InviteMessage msg) {
        final ProgressDialog pd = new ProgressDialog(context);
        String str1 = context.getResources().getString(R.string.Are_agree_with);
        final String str2 = context.getResources()
                .getString(R.string.Has_agreed_to);
        final String str3 = context.getResources()
                .getString(R.string.Agree_with_failure);
        pd.setMessage(str1);
        pd.setCanceledOnTouchOutside(false);
        pd.show();

        new Thread(new Runnable() {
            public void run() {
                // 调用sdk的同意方法
                try {
                    if (msg.getGroupId() == null) { // 同意好友请求
                        EMClient.getInstance().contactManager()
                                .acceptInvitation(msg.getFrom());
                    } else
                        // 同意加群申请
                        EMClient.getInstance().groupManager().acceptApplication(
                                msg.getFrom(), msg.getGroupId());
                    ((Activity) context).runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            pd.dismiss();
                            textView.setText(str2); //更改提示为已同意
                            msg.setStatus(InviteMesageStatus.AGREED);
                            // 更新db
                            ContentValues values = new ContentValues();
                            values.put(InviteMessgeDao.COLUMN_NAME_STATUS,
                                    msg.getStatus().ordinal());
                            messgeDao.updateMessage(msg.getId(), values);//更改状态为AGREED同意加好友
                            imageView.setVisibility(View.GONE);
                            relativeLayout.setEnabled(false);

                        }
                    });
                } catch (final Exception e) {
                    ((Activity) context).runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(context, str3 + e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            }
        }).start();
    }

    private static class ViewHolder {
        ImageView avator;
        TextView name;
        TextView reason;
        RelativeLayout status;
        LinearLayout groupContainer;
        TextView groupname;
        TextView mTvAGREE;
        ImageView mIvAGREE;
        // TextView time;
    }

}
